package com.dxg.msns.music.service.impl;

import com.dxg.msns.music.mapper.MusicFavorMapper;
import com.dxg.msns.music.mapper.MusicGradeMapper;
import com.dxg.msns.music.mapper.PlaylistMapper;
import com.dxg.msns.music.pojo.Music;
import com.dxg.msns.music.pojo.MusicGradeDTO;
import com.dxg.msns.music.pojo.MusicVo;
import com.dxg.msns.music.pojo.Playlist;
import com.dxg.msns.music.service.MusicService;
import com.dxg.msns.music.service.PlaylistService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PlaylistServiceImpl implements PlaylistService {
    @Autowired
    private MusicService musicService;
    @Autowired
    private PlaylistMapper playlistMapper;
    @Autowired
    private MusicGradeMapper    musicGradeMapper;
    @Autowired
    private MusicFavorMapper musicFavorMapper;
    @Override
    public List<Playlist> recommendPlaylist() {
        // 获取所有歌单
        List<Playlist> allPlaylists = this.playlistMapper.selectAll();

        // 过滤出公开歌单，isPublic 为 1 的歌单
        List<Playlist> publicPlaylists = allPlaylists.stream()
                .filter(p -> Integer.valueOf(1).equals(p.getIsPublic()))  // 只保留 isPublic == 1 的歌单
                .collect(Collectors.toList());
        // 计算每个公开歌单的平均评分
        Map<Playlist, Double> playlistAvgGradeMap = new HashMap<>();

        for (Playlist playlist : publicPlaylists) {
            double avgGrade = calculatePlaylistAvgGrade(playlist.getId());
            // 只记录有评分的歌单
                playlistAvgGradeMap.put(playlist, avgGrade);

        }

        // 排序：按照平均评分从高到低
        return playlistAvgGradeMap.entrySet().stream()
                .sorted(Map.Entry.<Playlist, Double>comparingByValue().reversed())
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());
    }

    /**
     * 根据歌单ID，计算该歌单内所有音乐的平均评分（只统计状态为0的评分）
     */
    @Override
    public double calculatePlaylistAvgGrade(String playlistId) {
        // 获取歌单下所有音乐ID
        List<String> musicIds = this.playlistMapper.selectMusicIdsByPlaylistId(playlistId);

        if (musicIds == null || musicIds.isEmpty()) return 0.0;

        // 获取这些音乐的评分信息
        List<MusicGradeDTO> grades = this.musicGradeMapper.selectByMusicIdes(musicIds);

        // 提取有效评分（状态为0）
        List<Integer> validGrades = grades.stream()
                .filter(g -> g.getStatus() != null && g.getStatus() == 0 && g.getMusicGrade() != null)
                .map(MusicGradeDTO::getMusicGrade)
                .collect(Collectors.toList());

        if (grades == null || grades.isEmpty()) return 0.0;

        if (validGrades.isEmpty()) return 0.0;

        return validGrades.stream()
                .mapToInt(Integer::intValue)
                .average()
                .orElse(0.0);
    }

    @Override
    public void createPlaylist(Playlist playlist) {
        System.out.println("创建播放列表参数: " + playlist);

        if (playlist.getId() == null) {
            playlist.setId(UUID.randomUUID().toString());
        }
        if (playlist.getCreateTime() == null) {
            playlist.setCreateTime(new Date());
        }
        if (playlist.getUpdateTime() == null) {
            playlist.setUpdateTime(new Date());
        }
        playlist.setIsPublic(playlist.getIsPublic());

        // 处理空的 musicIds 数组
        List<String> musicIds = playlist.getMusicIds();
        System.out.println("音乐 ID 列表: " + musicIds);
        if (musicIds == null || musicIds.isEmpty()) {
            playlist.setMusicIds(null);  // 设置为 null
        } else {
            for (String musicId : musicIds) {
                playlistMapper.insertMusicToPlaylist(playlist.getId(), musicId);
            }
        }

        // 插入播放列表基本信息
        try {
            playlistMapper.insert(playlist);
            System.out.println("播放列表插入成功");
        } catch (Exception e) {
            System.out.println("插入播放列表时发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }


    @Override
    public Playlist getPlaylistById(String id) {
        return playlistMapper.selectById(id);
    }

    @Override
    public List<Playlist> getPlaylistByUserId(String userId) {
        return playlistMapper.selectByUserId(userId);

    }

    @Override
    public List<Playlist> getAllPlaylists() {
        return playlistMapper.selectAll();
    }

    @Override
    public void updatePlaylist(Playlist playlist) {
        playlist.setUpdateTime(new Date());
        playlistMapper.update(playlist);
    }

    @Override
    @Transactional
    public void deletePlaylistById(String id) {
        playlistMapper.deletePlaylistById(id);  // 同时删除 playlist_music 表中关联项
        playlistMapper.deletePlaylistMusicByPlaylistId(id);  // 同时删除 playlist_music 表中关联项
    }

    @Override
    public void addMusicToPlaylist(String playlistId, String musicId) {
        playlistMapper.insertMusicToPlaylist(playlistId, musicId);
    }

    @Override
    public void removeMusicFromPlaylist(String playlistId, String musicId) {
        playlistMapper.deleteMusicFromPlaylist(playlistId, musicId);
    }

    @Override
    public List<String> getMusicIdsByPlaylistId(String playlistId) {
        return playlistMapper.selectMusicIdsByPlaylistId(playlistId);
    }

    @Override
    public List<MusicVo> getMusicByPlaylistId(String playlistId, String userId) {
        // 1. 获取歌单对应的音乐 ID 列表
        List<String> musicIdsByPlaylistId = getMusicIdsByPlaylistId(playlistId);

        // 2. 获取用户收藏的音乐 ID 列表
        List<String> favorIds = musicFavorMapper.queryByUid(userId);
        Set<String> favorSet = new HashSet<>(favorIds);

        // 3. 构建 MusicVo 列表
        List<MusicVo> musicVoList = new ArrayList<>();
        for (String musicId : musicIdsByPlaylistId) {
            Music music = musicService.queryMusicByMusicId(musicId);
            if (music != null) {
                int favorStatus = favorSet.contains(music.getId().toString()) ? 1 : 0;
                MusicVo musicVo = new MusicVo(music, favorStatus);
                musicVoList.add(musicVo);
            }
        }

        return musicVoList;
    }

    @Override
    public List<Music> getMusicByPlaylistIdAdmin(String playlistId) {
        List<String> musicIdsByPlaylistId = getMusicIdsByPlaylistId(playlistId);
        List<Music> musics = new ArrayList<>();
        for (String musicId : musicIdsByPlaylistId) {
            Music music = musicService.queryMusicByMusicId(musicId);
            musics.add(music);
        }
        return musics;
    }
}

